﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using System.Configuration;
using System.Web.Security;

namespace TireService.Website.Kunde
{
    public partial class Kundedata : System.Web.UI.Page
    {

        #region Public Properties

        public int CustomerId
        {
            get
            {
                if (ViewState["_customerid"] != null)
                    return (int)ViewState["_customerid"];
                else
                    return (int)Session["CustomerId"];
            }
            set
            {
                ViewState["_customerid"] = value;
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            // Test propertie
            //this.CustomerId = 10000;

            if (Page.IsPostBack != true)
            {
                // Get data for dropdownlists
                ddlCountry.DataSource = db.GetCountries();
                ddlCountry.ValueField = "CountryId";
                ddlCountry.TextField = "CountryName";
                ddlCountry.DataBind();

                LoadEditForm(db, this.CustomerId);
            }
        }

        protected void LoadEditForm(TireServiceDB db, int CustomerId)
        {
            // Reset UI message
            lMessage.Text = "";

            Customer customer = db.GetCustomer(CustomerId);

            if (customer != null)
            {
                // Set form fields
                // Customer info
                txtName.Text = customer.Name;
                txtAddress.Text = customer.Address;
                txtZipCode.Text = customer.ZipCode;
                txtCity.Text = customer.City;
                ddlCountry.Items.FindByValue(Convert.ToString(customer.CountryId)).Selected = true;
                txtSecondaryAddress.Text = customer.SecondaryAddress;
                txtSecondaryZipCode.Text = customer.SecondaryZipCode;
                txtSecondaryCity.Text = customer.SecondaryCity;
                txtPhone1.Text = customer.Phone1;
                ddlPhone1Type.Items.FindByValue(Convert.ToString(customer.Phone1Type)).Selected = true;
                if (customer.Phone2 != null) txtPhone2.Text = customer.Phone2;
                if (customer.Phone2 != null) ddlPhone2Type.Items.FindByValue(Convert.ToString(customer.Phone2Type)).Selected = true;
                txtEmail.Text = customer.Email;
            }
            else
            {
                // Error - customer could not be found
            }
        
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                TireServiceDB db = new TireServiceDB();

                // Update existing customer
                Customer customer = db.GetCustomer(this.CustomerId);

                customer.Name = txtName.Text;
                customer.Address = txtAddress.Text;
                customer.ZipCode = txtZipCode.Text;
                customer.City = txtCity.Text;
                //customer.OnAddressFrom = TimeSpan.Parse(txtOnAddressFrom.Text);
                //customer.OnAddressTo = TimeSpan.Parse(txtOnAddressTo.Text);
                customer.CountryId = Convert.ToInt32(ddlCountry.SelectedItem.Value);

                // Calculate longitude and latitude for address
                try
                {
                    string primaryAddress = txtAddress.Text + ", " + txtZipCode.Text + " " + txtCity.Text + ", " + db.GetCountryName(customer.CountryId);
                    double[] LongLatPrimary = HelperFunctions.GetLongLatCoordinates(primaryAddress, ConfigurationManager.AppSettings["MapKey"]);
                    customer.LongitudePrimary = LongLatPrimary[0];
                    customer.LatitudePrimary = LongLatPrimary[1];
                }
                catch (Exception)
                {
                    // Error calculating longitude and latitude - values will be set to null
                    customer.LongitudePrimary = null;
                    customer.LatitudePrimary = null;
                }


                if (txtSecondaryAddress.Text != "") customer.SecondaryAddress = txtSecondaryAddress.Text;
                if (txtSecondaryZipCode.Text != "") customer.SecondaryZipCode = txtSecondaryZipCode.Text;
                if (txtSecondaryCity.Text != "") customer.SecondaryCity = txtSecondaryCity.Text;
                if (txtSecondaryAddress.Text != "" & txtSecondaryZipCode.Text != "" & txtSecondaryCity.Text != "")
                {
                    // Calculate longitude and latitude for secondary address
                    try
                    {
                        string secondaryAddress = txtSecondaryAddress.Text + ", " + txtSecondaryZipCode.Text + " " + txtSecondaryCity.Text + ", " + db.GetCountryName(customer.CountryId);
                        double[] LongLatSecondary = HelperFunctions.GetLongLatCoordinates(secondaryAddress, ConfigurationManager.AppSettings["MapKey"]);
                        customer.LongitudeSecondary = LongLatSecondary[0];
                        customer.LatitudeSecondary = LongLatSecondary[1];
                    }
                    catch (Exception)
                    {
                        // Error calculating longitude and latitude - values will be set to null
                        customer.LongitudeSecondary = null;
                        customer.LatitudeSecondary = null;
                    }
                }
                else
                {
                    customer.LongitudeSecondary = null;
                    customer.LatitudeSecondary = null;
                }

                customer.Phone1 = txtPhone1.Text;
                customer.Phone1Type = Convert.ToInt32(ddlPhone1Type.SelectedItem.Value);
                if (txtPhone2.Text != "") customer.Phone2 = txtPhone2.Text;
                if (txtPhone2.Text != "") customer.Phone2Type = Convert.ToInt32(ddlPhone2Type.SelectedItem.Value);
                customer.Email = txtEmail.Text;

                // Commit changes to database
                db.SubmitChanges();

                if (customer.SyncToEconomic)
                {
                    // Sync with E-conomics
                    EconomicInterface ecoInterface = new EconomicInterface();
                    ecoInterface.UpdateDebtor(customer, db);
                }

                lMessage.Text = "Dine oplysninger blev gemt";

                // Dispose database connection
                db.Dispose();
            }
            catch (Exception ex)
            {
                if ((ex) is ArgumentException)
                {
                    // User error - arguments not valid - show error message
                    lMessage.Text = ((ArgumentException)ex).Message;
                }
                else
                {
                    // System error - show general error message
                    lMessage.Text = "Fejl opstod - venligst prøv igen";
                }
            }
        }

    }
}